package com.oxygen.pt.task;

import cn.hutool.core.lang.Pair;
import com.oxygen.pt.mapper.HyperbaricChamberMapper;
import com.oxygen.pt.utils.RedisConstants;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class CacheRefresher implements ApplicationRunner {

    @Resource
    private HyperbaricChamberMapper hyperbaricChamberMapper;

    @Resource
    private final StringRedisTemplate stringRedisTemplate;

    public CacheRefresher(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 氧舱缓存刷新，每一天凌晨刷新缓存
     */
    //@Scheduled(cron = "0 0 0 1/1 * ? ") // 每天刷新 "0 0 0 1/1 * ? "
    @Scheduled(fixedRate = 10_000)//每十秒刷新一次，用于测试
    public void chamberRefreshExecutor(){
        chamberRefresher();
    }

    /**
     * 刷新氧舱的缓存
     */
    public void chamberRefresher(){
        List<Pair<Integer, Integer>> pairs = hyperbaricChamberMapper.selectChamberInfo();
        //删除旧的缓存
        stringRedisTemplate.delete(RedisConstants.CHAMBER_INFORMATION);
        //遍历获得的信息，将数据存到redis缓存中
        for (Pair<Integer, Integer> pair : pairs) {
            //stringRedisTemplate要求所有的Hash操作参数必须为String类型
            //K: 氧舱编号  V：氧舱余量
            stringRedisTemplate.opsForHash().put(
                    RedisConstants.CHAMBER_INFORMATION,
                    String.valueOf(pair.getKey()),
                    String.valueOf(pair.getValue())
                    );
        }
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        chamberRefresher();
    }
}
